package com.niubi.yygh.orders.controller;

import com.niubi.yygh.common.result.R;
import com.niubi.yygh.enums.PaymentTypeEnum;
import com.niubi.yygh.orders.service.PaymentInfoService;
import com.niubi.yygh.orders.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author 牛俊杰
 */
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
  @Autowired
  WeixinService weixinService;
  @Autowired
  PaymentInfoService paymentInfoService;

  @GetMapping("/createNative/{orderId}")
  public R createNative(
          @ApiParam(name = "orderId", value = "订单id", required = true)
          @PathVariable("orderId") Long orderId) {
    Map<String,Object> map = weixinService.createNative(orderId);
    return R.ok().data(map);
  }

  @ApiOperation(value = "查询支付状态")
  @GetMapping("/queryPayStatus/{orderId}")
  public R queryPayStatus(
          @ApiParam(name = "orderId", value = "订单id", required = true)
          @PathVariable("orderId") Long orderId) {
    //1.根据订单id调用微信接口查询是否支付成功
    Map<String,String> resultMap = weixinService.queryWxPayStatus(orderId);
    //2.根据微信接口返回数据判断
    if (resultMap == null){
      return R.error().message("支付出错");
    }
    if ("SUCCESS".equals(resultMap.get("trade_state"))){
      //微信查询支付状态接口,返回订单交易号
      String out_trade_no = resultMap.get("out_trade_no");
      //调用方法支付记录状态和订单状态改为已经支付
      paymentInfoService.updateOrderStatus(out_trade_no, PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
      return R.ok().message("支付成功");
    }
    return R.ok().message("支付中");
  }
}
